/**
 * WebSocket 客户端封装
 * 
 * @author bugstack
 */
class AIWebSocketClient {
    constructor(url) {
        this.url = url;
        this.ws = null;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 3000;
        this.listeners = {
            onOpen: [],
            onMessage: [],
            onError: [],
            onClose: []
        };
    }
    
    /**
     * 连接 WebSocket
     */
    connect() {
        console.log('🔌 Connecting to:', this.url);
        
        this.ws = new WebSocket(this.url);
        
        this.ws.onopen = (event) => {
            console.log('✅ WebSocket connected');
            this.reconnectAttempts = 0;
            this.listeners.onOpen.forEach(cb => cb(event));
        };
        
        this.ws.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                console.log('📨 Received:', data.type, data.content ? `(${data.content.length} chars)` : '');
                this.listeners.onMessage.forEach(cb => cb(data));
            } catch (error) {
                console.error('❌ Parse error:', error);
            }
        };
        
        this.ws.onerror = (error) => {
            console.error('❌ WebSocket error:', error);
            this.listeners.onError.forEach(cb => cb(error));
        };
        
        this.ws.onclose = (event) => {
            console.log('🔌 WebSocket closed:', event.code, event.reason);
            this.listeners.onClose.forEach(cb => cb(event));
            this.handleReconnect();
        };
    }
    
    /**
     * 发送消息
     */
    send(data) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            const message = typeof data === 'string' ? data : JSON.stringify(data);
            this.ws.send(message);
            console.log('📤 Sent:', data.type || 'message');
        } else {
            console.error('❌ WebSocket is not connected');
        }
    }
    
    /**
     * 发送聊天消息
     */
    sendChat(content, enableTracing = false) {
        this.send({
            type: enableTracing ? 'trace' : 'chat',
            content: content,
            enableTracing: enableTracing,
            timestamp: Date.now()
        });
    }
    
    /**
     * 关闭连接
     */
    close() {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
    }
    
    /**
     * 自动重连
     */
    handleReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`🔄 Reconnecting... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            setTimeout(() => this.connect(), this.reconnectDelay);
        } else {
            console.error('❌ Max reconnect attempts reached');
        }
    }
    
    /**
     * 注册事件监听器
     */
    on(event, callback) {
        if (this.listeners[event]) {
            this.listeners[event].push(callback);
        }
    }
    
    /**
     * 移除事件监听器
     */
    off(event, callback) {
        if (this.listeners[event]) {
            this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
        }
    }
}
